package com.task.core.service.impl;

import java.util.*;
import javax.annotation.Resource;

import com.task.common.constant.ErrorCodeConstants;
import com.task.common.utils.bean.BeanUtils;
import com.task.core.domain.EngineInfo;
import com.task.core.service.EngineService;
import com.task.core.vo.resp.DeviceDetailRespVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import com.task.common.annotation.DataScope;
import com.task.common.core.domain.entity.SysDept;
import com.task.common.domain.info.KeyAndValue;
import com.task.common.exception.ServiceException;
import com.task.common.utils.SecurityUtils;
import com.task.core.domain.DeviceInfo;
import com.task.core.dto.request.DeviceRequestDTO;
import com.task.core.dto.response.DeviceAddResponseDTO;
import com.task.core.mapper.DeviceMapper;
import com.task.core.service.DeviceService;

/**
 * @author 迪迦.
 * @date 2024/11/4 17:25
 */
@Service("DeviceService")
public class DeviceServiceImpl implements DeviceService {

  @Resource
  private DeviceMapper deviceMapper;

  @Resource
  private EngineService engineService;

  @Override
  @DataScope(deptAlias = "dept", userAlias = "su")
  public List<DeviceInfo> getDeviceByPage(DeviceRequestDTO request) {
    //request.setOperationBy(SecurityUtils.checkAdmin());
    List<DeviceInfo> deviceByPage = deviceMapper.getDeviceByPage(request);
    for (DeviceInfo deviceInfo : deviceByPage) {
      deviceInfo.setEngineCodes(deviceMapper.getCanUseEngineCodesByDeviceCode(deviceInfo.getCode()));
    }
    return deviceByPage;
  }

  @Override
  @DataScope(deptAlias = "dept", userAlias = "su")
  public List<KeyAndValue> getDeviceForOption(DeviceRequestDTO request) {
    //request.setOperationBy(SecurityUtils.checkAdmin());
    return deviceMapper.getDeviceForOption(request);
  }


  @Transactional
  @Override
  public DeviceAddResponseDTO addDevice(DeviceRequestDTO request) {
    if (CollectionUtils.isEmpty(request.getDeviceNameAndSequence())) {
      throw new ServiceException("设备名称和序列号不能为空");
    }
    if (!ObjectUtils.isEmpty(request.getDeptCode())) {
      request.setOperationBy(SecurityUtils.getLoginUser().getUserId());
    } else {
      request.setDeptCode(SecurityUtils.getLoginUser().getDeptId().toString());
    }
    request.setOperationBy(SecurityUtils.getLoginUser().getUserId());
    List<String> deviceNameAndSequence = request.getDeviceNameAndSequence();
    List<Map<String, String>> deviceNameAndSequenceMap = new ArrayList<>();
    List<String> deviceNames = new ArrayList<>();

    for (String deviceSequence : deviceNameAndSequence) {
      String[] split = deviceSequence.split("\\|");
      //设备的名称
      if(ObjectUtils.isEmpty(split) || split.length !=2){
        throw new ServiceException(ErrorCodeConstants.DEVICE_SUPPORT_FORMAT.getMsg());
      }

      if(!ObjectUtils.isEmpty(split) &&
              !ObjectUtils.isEmpty(split[0]) &&
              !ObjectUtils.isEmpty(split[1])){
        deviceNames.add(split[0]);
        HashMap<String, String> map = new HashMap<>();
        map.put("deviceName",split[0]);
        map.put("deviceSeqNumber",split[1]);
        deviceNameAndSequenceMap.add(map);
      }else {
        throw new ServiceException(ErrorCodeConstants.DEVICE_SUPPORT_FORMAT_NOT_EMPTY.getMsg());
      }


    }
    List<String> deviceInfos = deviceMapper.checkDeviceCanAdd(deviceNames, request.getDeptCode());
    List<Map<String, String>> addNames = new ArrayList<>();
    List<String> repeatNames = new ArrayList<>();
    for (Map<String, String> entity : deviceNameAndSequenceMap) {
      if (deviceInfos.contains(entity.get("deviceName"))) {
        repeatNames.add(entity.get("deviceName"));
        continue;
      }
      Map<String, String> map = new HashMap<>();
      map.put("code", UUID.randomUUID().toString().replace("-", ""));
      map.put("name", entity.get("deviceName"));
      map.put("deviceSeqNumber",entity.get("deviceSeqNumber"));
      addNames.add(map);
    }


    if (!CollectionUtils.isEmpty(addNames)) {
      deviceMapper.addDevice(request, addNames);
      if (!CollectionUtils.isEmpty(request.getEngineCodes())) {
        for (Map<String, String> device : addNames) {
          deviceMapper.addDeviceEngineRelation(device.get("code"), request.getEngineCodes());
        }
      }
    }
    return new DeviceAddResponseDTO(repeatNames);
  }

  @Transactional
  @Override
  public void modifyDevice(DeviceRequestDTO request) {
    request.setOperationBy(SecurityUtils.getLoginUser().getUserId());
    if (!ObjectUtils.isEmpty(request.getDeptCode())) {
      request.setOperationBy(SecurityUtils.getLoginUser().getUserId());
    } else {
      request.setDeptCode(SecurityUtils.getLoginUser().getDeptId().toString());
    }
    Integer count = deviceMapper.checkDeviceNameCanAddByCode(request.getDeviceName(), request.getCode(),
        request.getDeptCode());
    if (count > 0) {
      throw new ServiceException("设备名称不能重复");
    }

    //删除关联引擎
    deviceMapper.deleteDeviceEngineRelation(request.getCode());
    //添加关联引擎
    deviceMapper.addDeviceEngineRelation(request.getCode(), request.getEngineCodes());
    Integer integer = deviceMapper.modifyDevice(request);
    if(integer == 0) {
      throw new ServiceException("code不存在");
    }
  }

  @Transactional
  @Override
  public void deleteDevice(String deviceCode, Long userId) {
    Integer integer = deviceMapper.deleteDevice(deviceCode, userId);
    if(integer == 0) {
      throw new ServiceException("code不存在");
    }
    //删除关联引擎
    deviceMapper.deleteDeviceEngineRelation(deviceCode);
  }

  @Override
  public Integer checkDevice(String deviceCode) {
    return deviceMapper.checkDevice(deviceCode);
  }

  @Override
  public DeviceInfo getDeviceByCode(String deviceCode) {
    return deviceMapper.getDeviceByCode(deviceCode);
  }

  @Override
  public DeviceInfo getDeviceByName(String deviceName, Long deptCode) {
    return deviceMapper.getDeviceByName(deviceName, deptCode);
  }

  @Override
  public List<DeviceInfo> getDeviceListByGroupCodes(List<String> groupCodes) {
    return deviceMapper.getDeviceListByGroupCodes(groupCodes);
  }

  @Override
  public List<String> getCanUseEngineCodesByDeviceCode(String deviceCode) {
    return deviceMapper.getCanUseEngineCodesByDeviceCode(deviceCode);
  }

  @Override
  public List<KeyAndValue> getChildDeptByAdminCreate() {
    List<KeyAndValue> keyAndValues = new ArrayList<>();
    if (SecurityUtils.isAdmin()) {
      keyAndValues = deviceMapper.getAllDeptAdmin();
    }else {
      List<SysDept> deptList = deviceMapper.getAllDept();
      SysDept sysDept = getChildCompany(deptList, SecurityUtils.getDeptId());
      keyAndValues.add(new KeyAndValue(sysDept.getDeptName(), sysDept.getDeptId().toString()));
    }
    return keyAndValues;
  }

  @Override
  @DataScope(deptAlias = "dept",userAlias = "su")
  public DeviceDetailRespVo getDeviceDetailByCode(String deviceCode) {
    DeviceRequestDTO deviceRequestDTO = new DeviceRequestDTO();
    deviceRequestDTO.setCode(deviceCode);
    DeviceInfo device = deviceMapper.getDeviceDetailByCode(deviceRequestDTO);
    if(ObjectUtils.isEmpty(device)){
      throw new ServiceException(ErrorCodeConstants.DEVICE_NOT_EXIST.getMsg());
    }
    DeviceDetailRespVo respVo = new DeviceDetailRespVo();
    BeanUtils.copyProperties(device,respVo);
    List<String> engineCodes = deviceMapper.getCanUseEngineCodesByDeviceCode(deviceCode);
    if(!CollectionUtils.isEmpty(engineCodes)){
      List<EngineInfo> engines = engineService.getEngineByCodes(engineCodes);
      respVo.setEngineInfos(engines);
    }
    return respVo;
  }

  private SysDept getChildCompany(List<SysDept> deptList, Long deptId) {
    SysDept sysDept = deptList.stream().filter(f -> f.getDeptId().equals(deptId)).findFirst().orElse(null);
    if (ObjectUtils.isEmpty(sysDept)) {
      throw new ServiceException("获取子公司错误");
    }
    if (sysDept.getParentId() == 100) {
      //说明是子公司
      return sysDept;
    }else {
      return getChildCompany(deptList, sysDept.getParentId());
    }
  }
}
